/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Dicionario;

import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Fatec
 */
public class DicionarioMidlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;

    private Vector descrições = new Vector();

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form form;
    private ImageItem imageItem;
    private StringItem stringItem;
    private TextField palavraTextField;
    private List list;
    private Form detalhesForms;
    private StringItem TituloStringItem;
    private StringItem DescStringItem;
    private Command exitCommand;
    private Command significadoItemCommand;
    private Command exitCommand1;
    private Command detalheItemCommand;
    private Command itemCommand;
    private Command exitCommand2;
    private Image imagem;
//</editor-fold>//GEN-END:|fields|0|

    /**
     * The DicionarioMidlet constructor.
     */
    public DicionarioMidlet() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display; if
     * <code>null</code>, then
     * <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a
     * particular displayable.
     *
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == detalhesForms) {//GEN-BEGIN:|7-commandAction|1|42-preAction
            if (command == exitCommand2) {//GEN-END:|7-commandAction|1|42-preAction
                // write pre-action user code here
                switchDisplayable(null, getList());//GEN-LINE:|7-commandAction|2|42-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|20-preAction
        } else if (displayable == form) {
            if (command == exitCommand) {//GEN-END:|7-commandAction|3|20-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|4|20-postAction
                // write post-action user code here
            } else if (command == significadoItemCommand) {//GEN-LINE:|7-commandAction|5|22-preAction
                // write pre-action user code here
                switchDisplayable(null, getList());//GEN-LINE:|7-commandAction|6|22-postAction
                
                String palv = palavraTextField.getString();
                String url = "http://dicionario-aberto.net/search-xml/"+palv;
                try{
                    getList().deleteAll();
                    StreamConnection connection = (StreamConnection) Connector.open(url, Connector.READ_WRITE);
                    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
                    saxParser.parse(connection.openDataInputStream(), new DefaultHandler(){
                        private String currentName = "";
                        public void startElement(String uri, String lName, String name, Attributes att) throws SAXException {
                            currentName = name;
                        }
                        public void characters(char[] ch, int start, int length) throws SAXException{
                            String chars = new String(ch, start, length).trim();
                            if(chars.length()>0){
                                if (currentName.equals("orth")){
                                    getList().append(chars, getImagem());
                                }else if(currentName.equals("def")){
                                    descrições.addElement(chars);
                                }
                            }
                        }
                });
                }catch(Exception error){
                    Alert mensagem = new Alert("Falha");
                    mensagem.setString(error.getMessage()); mensagem.setTimeout(3000);
                    getDisplay().setCurrent(mensagem);
                }
            }//GEN-BEGIN:|7-commandAction|7|17-preAction
        } else if (displayable == list) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|7|17-preAction
                // write pre-action user code here
                listAction();//GEN-LINE:|7-commandAction|8|17-postAction
                // write post-action user code here
            } else if (command == detalheItemCommand) {//GEN-LINE:|7-commandAction|9|34-preAction
                // write pre-action user code here
               
                switchDisplayable(null, getDetalhesForms());//GEN-LINE:|7-commandAction|10|34-postAction
                String titulo = getList().getString(getList().getSelectedIndex());
                String desc = (String) descrições.elementAt(getList().getSelectedIndex());
                TituloStringItem.setText(titulo);
                DescStringItem.setText(desc);
                
            } else if (command == exitCommand1) {//GEN-LINE:|7-commandAction|11|24-preAction
                // write pre-action user code here
                switchDisplayable(null, getForm());//GEN-LINE:|7-commandAction|12|24-postAction
                // write post-action user code here

            }//GEN-BEGIN:|7-commandAction|13|7-postCommandAction
        }//GEN-END:|7-commandAction|13|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|14|
//</editor-fold>//GEN-END:|7-commandAction|14|


//<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initialized instance of form component.
     *
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form("Dicion\u00E1rio de Portugu\u00EAs", new Item[]{getImageItem(), getStringItem(), getPalavraTextField()});//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getExitCommand());
            form.addCommand(getSignificadoItemCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: list ">//GEN-BEGIN:|15-getter|0|15-preInit
    /**
     * Returns an initialized instance of list component.
     *
     * @return the initialized component instance
     */
    public List getList() {
        if (list == null) {//GEN-END:|15-getter|0|15-preInit
            // write pre-init user code here
            list = new List("Escolha da Palavra", Choice.IMPLICIT);//GEN-BEGIN:|15-getter|1|15-postInit
            list.addCommand(getExitCommand1());
            list.addCommand(getDetalheItemCommand());
            list.setCommandListener(this);//GEN-END:|15-getter|1|15-postInit
            // write post-init user code here
        }//GEN-BEGIN:|15-getter|2|
        return list;
    }
//</editor-fold>//GEN-END:|15-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: listAction ">//GEN-BEGIN:|15-action|0|15-preAction
    /**
     * Performs an action assigned to the selected list element in the list
     * component.
     */
    public void listAction() {//GEN-END:|15-action|0|15-preAction
        // enter pre-action user code here
        String __selectedString = getList().getString(getList().getSelectedIndex());//GEN-LINE:|15-action|1|15-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|15-action|2|
//</editor-fold>//GEN-END:|15-action|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|19-getter|0|19-preInit
    /**
     * Returns an initialized instance of exitCommand component.
     *
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|19-getter|0|19-preInit
            // write pre-init user code here
            exitCommand = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|19-getter|1|19-postInit
            // write post-init user code here
        }//GEN-BEGIN:|19-getter|2|
        return exitCommand;
    }
//</editor-fold>//GEN-END:|19-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: significadoItemCommand ">//GEN-BEGIN:|21-getter|0|21-preInit
    /**
     * Returns an initialized instance of significadoItemCommand component.
     *
     * @return the initialized component instance
     */
    public Command getSignificadoItemCommand() {
        if (significadoItemCommand == null) {//GEN-END:|21-getter|0|21-preInit
            // write pre-init user code here
            significadoItemCommand = new Command("Buscar Palavra", "<nulo>", Command.ITEM, 0);//GEN-LINE:|21-getter|1|21-postInit
            // write post-init user code here
        }//GEN-BEGIN:|21-getter|2|
        return significadoItemCommand;
    }
//</editor-fold>//GEN-END:|21-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand1 ">//GEN-BEGIN:|23-getter|0|23-preInit
    /**
     * Returns an initialized instance of exitCommand1 component.
     *
     * @return the initialized component instance
     */
    public Command getExitCommand1() {
        if (exitCommand1 == null) {//GEN-END:|23-getter|0|23-preInit
            // write pre-init user code here
            exitCommand1 = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|23-getter|1|23-postInit
            // write post-init user code here
        }//GEN-BEGIN:|23-getter|2|
        return exitCommand1;
    }
//</editor-fold>//GEN-END:|23-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem ">//GEN-BEGIN:|29-getter|0|29-preInit
    /**
     * Returns an initialized instance of imageItem component.
     *
     * @return the initialized component instance
     */
    public ImageItem getImageItem() {
        if (imageItem == null) {//GEN-END:|29-getter|0|29-preInit
            // write pre-init user code here
            imageItem = new ImageItem("", getImagem(), ImageItem.LAYOUT_DEFAULT, "<Imagem perdida>");//GEN-LINE:|29-getter|1|29-postInit
            // write post-init user code here
        }//GEN-BEGIN:|29-getter|2|
        return imageItem;
    }
//</editor-fold>//GEN-END:|29-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|31-getter|0|31-preInit
    /**
     * Returns an initialized instance of stringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|31-getter|0|31-preInit
            // write pre-init user code here
            stringItem = new StringItem("Digite a palavra:", "");//GEN-LINE:|31-getter|1|31-postInit
            // write post-init user code here
        }//GEN-BEGIN:|31-getter|2|
        return stringItem;
    }
//</editor-fold>//GEN-END:|31-getter|2|
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: palavraTextField ">//GEN-BEGIN:|32-getter|0|32-preInit
    /**
     * Returns an initialized instance of palavraTextField component.
     *
     * @return the initialized component instance
     */
    public TextField getPalavraTextField() {
        if (palavraTextField == null) {//GEN-END:|32-getter|0|32-preInit
            // write pre-init user code here
            palavraTextField = new TextField("", "", 32, TextField.ANY);//GEN-LINE:|32-getter|1|32-postInit
            // write post-init user code here
        }//GEN-BEGIN:|32-getter|2|
        return palavraTextField;
    }
//</editor-fold>//GEN-END:|32-getter|2|
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imagem ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initialized instance of imagem component.
     *
     * @return the initialized component instance
     */
    public Image getImagem() {
        if (imagem == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|30-getter|1|30-@java.io.IOException
                imagem = Image.createImage("/imagens/Eurelio.jpg");
            } catch (java.io.IOException e) {//GEN-END:|30-getter|1|30-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|30-getter|2|30-postInit
            // write post-init user code here
        }//GEN-BEGIN:|30-getter|3|
        return imagem;
    }
//</editor-fold>//GEN-END:|30-getter|3|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: detalheItemCommand ">//GEN-BEGIN:|33-getter|0|33-preInit
    /**
     * Returns an initialized instance of detalheItemCommand component.
     *
     * @return the initialized component instance
     */
    public Command getDetalheItemCommand() {
        if (detalheItemCommand == null) {//GEN-END:|33-getter|0|33-preInit
            // write pre-init user code here
            detalheItemCommand = new Command("Significado", Command.ITEM, 0);//GEN-LINE:|33-getter|1|33-postInit
            // write post-init user code here
        }//GEN-BEGIN:|33-getter|2|
        return detalheItemCommand;
    }
//</editor-fold>//GEN-END:|33-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: detalhesForms ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initialized instance of detalhesForms component.
     *
     * @return the initialized component instance
     */
    public Form getDetalhesForms() {
        if (detalhesForms == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            detalhesForms = new Form("Significado da Palavra", new Item[]{getTituloStringItem(), getDescStringItem()});//GEN-BEGIN:|35-getter|1|35-postInit
            detalhesForms.addCommand(getExitCommand2());
            detalhesForms.setCommandListener(this);//GEN-END:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return detalhesForms;
    }
//</editor-fold>//GEN-END:|35-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: TituloStringItem ">//GEN-BEGIN:|36-getter|0|36-preInit
    /**
     * Returns an initialized instance of TituloStringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getTituloStringItem() {
        if (TituloStringItem == null) {//GEN-END:|36-getter|0|36-preInit
            // write pre-init user code here
            TituloStringItem = new StringItem("Palavra:", "");//GEN-LINE:|36-getter|1|36-postInit
            // write post-init user code here
        }//GEN-BEGIN:|36-getter|2|
        return TituloStringItem;
    }
//</editor-fold>//GEN-END:|36-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: DescStringItem ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initialized instance of DescStringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getDescStringItem() {
        if (DescStringItem == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            DescStringItem = new StringItem("Significado:", "");//GEN-LINE:|37-getter|1|37-postInit
            // write post-init user code here
        }//GEN-BEGIN:|37-getter|2|
        return DescStringItem;
    }
//</editor-fold>//GEN-END:|37-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: itemCommand ">//GEN-BEGIN:|38-getter|0|38-preInit
    /**
     * Returns an initialized instance of itemCommand component.
     *
     * @return the initialized component instance
     */
    public Command getItemCommand() {
        if (itemCommand == null) {//GEN-END:|38-getter|0|38-preInit
            // write pre-init user code here
            itemCommand = new Command("Item", Command.ITEM, 0);//GEN-LINE:|38-getter|1|38-postInit
            // write post-init user code here
        }//GEN-BEGIN:|38-getter|2|
        return itemCommand;
    }
//</editor-fold>//GEN-END:|38-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand2 ">//GEN-BEGIN:|41-getter|0|41-preInit
    /**
     * Returns an initialized instance of exitCommand2 component.
     *
     * @return the initialized component instance
     */
    public Command getExitCommand2() {
        if (exitCommand2 == null) {//GEN-END:|41-getter|0|41-preInit
            // write pre-init user code here
            exitCommand2 = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|41-getter|1|41-postInit
            // write post-init user code here
        }//GEN-BEGIN:|41-getter|2|
        return exitCommand2;
    }
//</editor-fold>//GEN-END:|41-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

}
